<?php

namespace App\Http\Controllers\Api;

use App\Libraries\Error;
use App\Models\Company;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Models\SmsCode;
use App\Models\User;
use Firebase\JWT\JWT;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\DB;

class LoginController extends ApiController
{

    protected $redirectTo = '/';
    

    public function register(Request $request){
        $mobile = $request->mobile;
        $mobileCode = $request->mobileCode;
        $password = $request->password;
        $name = $request->name;
        $codeinfo = SmsCode::where('mobile',$mobile)->orderBy('id','desc')->get();
        $userInfo = User::where('mobile',$mobile)->where('status',1)->first();
        if(!empty($userInfo)){
            return showError(Error::ERR_ERROR,"","已经注册,请直接登陆");
        }
        if((isset($codeinfo[0]['code']) && $mobileCode == $codeinfo[0]['code'])) {
            DB::beginTransaction();
            $company = new Company();
            $company->company_name = $request->company_name;
            $company->industry_type = $request->industry_type;
            $company->personnel_size = $request->personnel_size;
            $company->ctime = time();
            $company->mtime = time();
            $company->save();
            if (!$company->company_id) {
                DB::rollBack();
                return showError(Error::ERR_ERROR,'','插入公司失败');
            }
            $user = new User();
            $user->name = $name;
            $user->mobile = $mobile;
            $user->password = md5($mobile.$password);
            $user->company_id = $company->company_id;
            $user->save();
            if (!$user->uid) {
                DB::rollBack();
                return showError(Error::ERR_ERROR,'','插入用户失败');
            }
            Company::where('company_id',$company->company_id)->update(['uid'=>$user->uid]);

            DB::commit();
            return showError(Error::ERR_OK);
        } else {
            return showError(Error::ERR_ERROR,"","手机验证码错误");
        }

    }

    public function isregister(Request $request) {
        $mobile = $request->mobile;
        $user = User::where('mobile',$mobile)->where('status',1)->first();
        $is_register = 2;
        if ($user) {
            $is_register = 1;
        }

        return showError(Error::ERR_OK,['is_register'=>$is_register]);
    }

    public function getcompany(Request $request)
    {
        // 搜索内容
        $where = [];
        $company_name = $request->input('company_name');
        if (!empty($company_name))
        {
            $where['company_name'] = $company_name;
        }

        $where['status'] = 1;

        $list = Company::getList($where);

        return showError(Error::ERR_OK,['list'=>$list]);
    }

    //手机号、验证码登陆
    public function Login(Request $request) {
        $mobile  = $request->mobile;
        $mobileCode = $request->mobileCode;
        $password = $request->password;
//        $this->validate($request, [
//            'mobile' => 'bail|required',
//            'mobileCode' => 'bail|required',
//        ]);
        if (empty($mobile)) {
            return showError(Error::ERR_ERROR, null, "无效的手机号");
        }

        $userInfo = User::where('mobile',$mobile)->where('status',1)->first();
        if(empty($userInfo)){
            return showError(Error::ERR_ERROR,"","请先注册在登陆");
        }

        if (!empty($mobileCode)) {
            $codeinfo = SmsCode::where('mobile',$mobile)->orderBy('id','desc')->get();

            if((isset($codeinfo[0]['code']) && $mobileCode == $codeinfo[0]['code'])) {
                //生成token
                $time = time();
                $payload = [
                    'iat' => $time,  //签发时间
                    'nbf' => $time,  //时间点后才能访问
                    'exp' => $time + 2629743, //过期时间 一个月
                    'data' => $userInfo,
                ];
                $token = JWT::encode($payload, env('JWT_KEY'));

                return showError(Error::ERR_OK,[ 'token' => $token ],"登陆成功");
            }else{
                return showError(Error::ERR_ERROR,"","手机验证码错误");
            }
        } elseif(!empty($password)) {
            if($userInfo['password']== md5($mobile.$password)){
                //生成token
                $time = time();
                $payload = [
                    'iat' => $time,  //签发时间
                    'nbf' => $time,  //时间点后才能访问
                    'exp' => $time + 2629743, //过期时间 一个月
                    'data' => $userInfo,
                ];
                $token = JWT::encode($payload, env('JWT_KEY'));

                return showError(Error::ERR_OK,[ 'token' => $token ],"登陆成功");
            } else {
                return showError(Error::ERR_ERROR,"","密码错误");
            }
        }


    }

    public function sendSms(Request $request){
        $mobile = $request->mobile;

        try {
            $code = rand(1000,9999);
            $data = array(
                'code' => $code,
                'mobile' => $mobile,
                'extra' => 'login',
                'result' => 1,
                'ctime' => time(),
                'mtime' => time(),
            );
            SmsCode::create($data);
            $res = $this->sendMessage($mobile,$code);
            if($res['Code'] == 'OK'){
                return showError(Error::ERR_OK,'','验证码已发送');
            }else{
                return showError(Error::ERR_SYSTEM_ERROR,'','验证码发送失败');
            }

        } catch (Exception $e) {

        }
    }

    /**
     * 发送验证码
     *
     * $mobile  @ 手机号 多个逗号分隔
     * $number  @ 验证码号
     */
    protected function sendMessage($mobile, $number){

        AlibabaCloud::accessKeyClient(env('accessKeyId'), env('accessSecret'))
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $mobile,
                        'SignName'=>env('MESSAGE_SIGN'),
                        'TemplateCode'=>env('TemplateCode'),
                        'TemplateParam'=>json_encode(["code"=>$number])
                    ],
                ])
                ->request();
//            print_r([
////                'accessKeyId'=>env('accessKeyId'),
////                'accessSecret'=>env('accessSecret'),
//                'SignName'=>env('MESSAGE_SIGN'),
//                'TemplateCode'=>env('TemplateCode'),
//                'TemplateParam'=>json_encode(["code"=>$number]),
//                'PhoneNumbers'=>$mobile,
//            ]);
//            print_r($result->toArray());
            return $result->toArray();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }

    }

    public function post_data_curl($url, $data, $isMulitArray = 0) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_TIMEOUT, 180);

        curl_setopt($ch, CURLOPT_POST, 1);
        if ($isMulitArray) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }

    /**
     * 绑定手机
     */
//    public function mobile(Request $request)
//    {
//        $code = $request->code;
//        $encryptedData = $request->encryptedData;
//        $iv = $request->iv;
//        if(empty($code)){
//            return showError(Error::ERR_ERROR, null, "无效的code!");
//        }
//
//        $oauth = $this->getOauth($code);
//        $data = [];
//        if(isset($oauth['session_key'])) {
//            $data = $this->decryptWXdata($encryptedData,$oauth['session_key'],$iv);
//            $data = json_decode($data,true);
//            if (!$data) {
//                $data = $this->decryptWXdata($encryptedData,$oauth['session_key'],$iv);
//                $data = json_decode($data,true);
//                if (!$data) {
//                    $data = $this->decryptWXdata($encryptedData,$oauth['session_key'],$iv);
//                    $data = json_decode($data,true);
//                }
//            }
//        }
//
//        if(!$data){
//            return showError(Error::ERR_ERROR, null, "授权异常，请再试一次");
//        }
//        $openId = isset($oauth['openid'])?$oauth['openid']:'';
//        $mobile = isset($data['phoneNumber'])?$data['phoneNumber']:'';
//        //更新user表 手机号
//        $userInfo = User::where('open_id',$openId)->where('status',1)->update(['mobile'=>$mobile]);
//
//
//        return showError(Error::ERR_OK,['mobile'=>$mobile]);
//    }

    //更新用户信息
//    public function userInfo(Request $request) {
//        if (!$request->token) {
//            return showError(Error::ERR_ERROR, null, "无效的token!");
//        }
//        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
//        $exp = $userInfo->exp;
//        if (time() > $exp) {
//            return showError(Error::ERR_TOKEN_ERROR);
//        }
//        $userInfo = (array)$userInfo->data;
//        $uid = $userInfo['uid'];
//        $user = User::where('uid',$uid)->where('status',1)->first();
//        if (empty($user)) {
//            return showError(Error::ERR_TOKEN_ERROR);
//        }
////        $uid = '29221';
//        $data = [
//            'username' => $request->nickName,
//            'nickname' => $request->nickName,
//            'gender'   => $request->gender,
//            'city'     => $request->city,
//            'province' => $request->province,
//            'country'  => $request->country,
//            'avatar'   => $request->avatarUrl,
//        ];
//        User::where('uid',$uid)->update($data);
//        return showError(Error::ERR_OK);
//
//    }

    /**
     * 是否绑定信息
     */
//    public function isbind(Request $request)
//    {
//        if (!$request->token) {
//            return showError(Error::ERR_ERROR, null, "无效的token!");
//        }
//        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
//        $exp = $userInfo->exp;
//        if (time() > $exp) {
//            return showError(Error::ERR_TOKEN_ERROR);
//        }
//        $userInfo = (array)$userInfo->data;
//        $uid = $userInfo['uid'];
//        $user = User::where('uid',$uid)->where('status',1)->first();
//        if (empty($user)) {
//            return showError(Error::ERR_TOKEN_ERROR);
//        }
//        $is_user_mobile = 2;
//        if (!empty($user['mobile'])) {
//            $is_user_mobile = 1;
//        }
//
//
//        return showError(Error::ERR_OK,['is_user_mobile'=>$is_user_mobile]);
//    }

    /**
     * 个人中心
     */
//    public function personal(Request $request)
//    {
//        if (!$request->token) {
//            return showError(Error::ERR_ERROR, null, "无效的token!");
//        }
//        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
//        $exp = $userInfo->exp;
//        if (time() > $exp) {
//            return showError(Error::ERR_TOKEN_ERROR);
//        }
//        $userInfo = (array)$userInfo->data;
//        $uid = $userInfo['uid'];
//        $user = User::where('uid',$uid)->where('status',1)->first();
//        if (empty($user)) {
//            return showError(Error::ERR_TOKEN_ERROR);
//        }
////        $uid = '29367';
//        //设备数 种植面积 作物
//        $equipments = EquipmentUser::where('uid',$uid)->where('status',1)->get();
//        $device_count = count($equipments);
//        $area = 0;
//        $cropsname = '';
//        if ($device_count > 0) {
//            foreach ($equipments as $k=>$v) {
////                $equipment = Equipment::find($v['eid']);
//                $greenhouse = GreenhouseEquipment::where('eid',$v['eid'])->where('status',1)->orderby('geid','desc')->first();
//                $gh = GreenHouse::where('gid',$greenhouse['gid'])->first();
//                $area += isset($gh['gh_area'])?$gh['gh_area']:0;
//                $cropsname .= $gh['crops_name'].' ';
//            }
//        }
//
//        return showError(Error::ERR_OK,['device_count'=>$device_count,'area'=>$area,'cropsname'=>$cropsname]);
//    }

}
